 <?php
require_once 'Database.class.php';
class Watched extends Database {
	public function __construct() {
		parent::__construct();
		parent::connect();
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $videoId
	 * @param unknown_type $userId
	 */
	public function checkWatched($videoId = NULL, $userId = NULL) {	
		$query = 'SELECT * 
				 FROM watched w	
				 WHERE w.video_id = "'.$videoId.'"
						AND w.user_id = "'.$userId.'"';
		$result = $this->fetchTable($query);
		if(count($result))
			return TRUE;
		else
			return FALSE;	
	}
	
	
	public function insertWatched($videoId = NULL, $userId = NULL){
		$query = 'INSERT  INTO watched(video_id, user_id,  date_created, date_updated)
						VALUES("'.$videoId.'", "'.$userId.'", SYSDATE(), SYSDATE())';		
			return $this->executeQuery($query);
		
	}
	
	public function getDecreaseVideo($userId = NULL, $tableName = NULL) {
		$videoId = '';
		$query = '';
		if( $tableName == 'liked'){		
			$query = 	'SELECT t.video_id video_id
						FROM `'.$tableName.'` t 
						WHERE t.user_id =  "'.$userId.'" 
						AND  t.like_flg = 1 
						AND t.count>0 
						ORDER BY t.date_created ASC
						LIMIT 0, 1';
		}else{
			$query = 	'SELECT t.video_id video_id
						FROM `'.$tableName.'` t 
						WHERE t.user_id =  "'.$userId.'"
						AND t.count>0 
						ORDER BY t.date_created ASC
						LIMIT 0, 1';
		}
		
		$result =  $this->fetchTable($query, 2);		

		if($result ){
			$videoId = $result[0]['video_id'];
		}
		return $videoId; 
	}

	public function updateCount($userId = NULL, $videoId = NULL, $tableName = NULL) {
		$query = '';
		if($tableName == 'liked'){
			$query = 'UPDATE '.$tableName.' 
				SET `count`= `count`-1
				WHERE user_id =  "'.$userId.'"
					AND video_id = "'.$videoId.'"
					AND like_flg = 1
					AND `count`>0';
		}
		else {
			$query = 'UPDATE '.$tableName.'  
				SET `count`= `count`-1
				WHERE user_id =  "'.$userId.'"
					AND video_id = "'.$videoId.'"
					AND `count`>0';
		}		
		return $this->executeQuery($query);
	}
	public function watchCouter($userId = NULL) {			
			$query = 	'SELECT distinct(w.user_id), w.video_id
						FROM `watched` w 
						WHERE w.user_id =  "'.$userId.'"';			
			$result = $this->fetchTable($query, 2);
			
			return count($result);
		}
	
}
